package com.wf.ew.system.controller;

import com.wf.ew.common.BaseController;
import com.wf.ew.common.JsonResult;
import com.wf.ew.common.PageResult;
import com.wf.ew.common.constant.UserConstant;
import com.wf.ew.common.exception.BusinessException;
import com.wf.ew.common.shiro.EndecryptUtil;
import com.wf.ew.common.utils.PoiUtil;
import com.wf.ew.system.model.Company;
import com.wf.ew.system.model.Role;
import com.wf.ew.system.model.User;
import com.wf.ew.system.service.CompanyService;
import com.wf.ew.system.service.RoleService;
import com.wf.ew.system.service.UserService;
import net.sf.json.JSONArray;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户管理
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private CompanyService companyService;

    @RequiresPermissions("user:view")
    @RequestMapping
    public String user(Model model) {
//        List<Role> role2s = roleService.list();
        List<Role> roles = roleService.list(null,getLoginUser());
        model.addAttribute("roles", roles);

        List<Company> list = companyService.list(null,getLoginUser());
        model.addAttribute("gs_list",list);
        return "system/user.html";
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("user:view")
    @RequestMapping(value = "/list", produces = {"text/html;charset=UTF-8;"})
    @ResponseBody
    public String list(PageResult<T> page, User user){
        return userService.list(page, user, getLoginUser());
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/userNameUnique")
    @ResponseBody
    public JsonResult userNameUnique(User user){
        return userService.userNameUnique(user);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("user:view")
    @RequestMapping(value = "/ajaxList", produces = {"text/html;charset=UTF-8;"})
    @ResponseBody
    public String ajaxList(User user){
        return JSONArray.fromObject(userService.list(user, getLoginUser())).toString();
    }

    /**
     * 修改用户状态
     **/
    @RequiresPermissions("user:update")
    @ResponseBody
    @RequestMapping("/updateState")
    public JsonResult updateState(User user) {
        return userService.udpateState(user,getLoginUser());
    }

    /**
     * 重置密码
     **/
    @RequiresPermissions("user:modifyPsw")
    @ResponseBody
    @RequestMapping("/restPsw")
    public JsonResult resetPsw(User user,boolean deft) {
        return userService.udpatePsw(user, getLoginUser(),deft);
    }
    /*
     * 新增
     */
    @RequiresPermissions("user:add")
    @ResponseBody
    @RequestMapping("/add")
    public JsonResult add(Model model, User user, String roleIds) {
        user.setState("正常");
        user.setPassword(EndecryptUtil.encrytMd5(UserConstant.DEFAULT_PSW, 3));
        return userService.add(user, getRoleIds(roleIds), getLoginUser());
    }

    /**
     * 修改
     **/
    @RequiresPermissions("user:update")
    @ResponseBody
    @RequestMapping("/update")
    public JsonResult update(Model model, User user) {
        return userService.update(user, getLoginUser());
    }

    /**
     * 批量删除
     **/
    @RequiresPermissions("user:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(User user ) {
        return userService.delete(user, getLoginUser());
    }

    /**
     * 用逗号分割角色
     */
    private List<Integer> getRoleIds(String rolesStr) {
        List<Integer> roleIds = new ArrayList<>();
        if (rolesStr != null) {
            String[] split = rolesStr.split(",");
            for (String t : split) {
                try {
                    roleIds.add(Integer.parseInt(t));
                } catch (Exception e) {
                }
            }
        }
        return roleIds;
    }

    /**
     * 导入用户
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("user:update")
    @ResponseBody
    @RequestMapping("/import")
    public JsonResult importData(MultipartFile file) throws IOException {
        List<Role> roleList = roleService.list();
        List<String[]> list = PoiUtil.importData(file.getInputStream(), 1, 0);
        for (int i = 0; i < list.size(); i++) {
            String[] strs = list.get(i);
            User user = new User();
            user.setPassword(EndecryptUtil.encrytMd5(UserConstant.DEFAULT_PSW, 3));
            user.setName(strs[0]);
            user.setNickName(strs[1]);
            user.setState("正常");
            user.setSex(strs[2]);
            user.setCompanyId(getLoginUser().getCompanyId());
            // 获取角色id
            String[] split = strs[3].split(",");
            List<Integer> roleIds = new ArrayList<>();
            for (String roleName : split) {
                Role role = getRoleByName(roleList, roleName);
                if (role == null) {
                    throw new BusinessException("第" + (i + 2) + "行角色" + roleName + "不存在");
                }
                roleIds.add(role.getRoleId());
            }
            // 添加
            userService.addUser(user, roleIds,getLoginUser());
        }
        return JsonResult.ok("导入成功");
    }

    private Role getRoleByName(List<Role> roleList, String roleName) {
        for (Role role : roleList) {
            if (role.getRoleName().equals(roleName)) {
                return role;
            }
        }
        return null;
    }
}
